function getCookie(objName)
{
    var arrStr = document.cookie.split("; ");
    for(var i = 0;i < arrStr.length;i ++){
        var temp = arrStr[i].split("=");
        if(temp[0] == objName) {
            return unescape(temp[1]);//返回一个包含charstring内容的字符串值
        }
    }
}



function setCookie(name, value, expires, path, domain) {
    if(!expires) expires = -1;
    if(!path) path = "/";
    var d = "" + name + "=" + value;

    var e;
    if (expires < 0) {
        e = "";
    } else if (expires == 0) {
        var f = new Date(1970, 1, 1);
        e = ";expires=" + f.toUTCString();
    } else {
        var now  = new Date();
        var f = new Date(now.getTime()  + expires * 86400000);
        e = ";expires=" + f.toUTCString();
    }
    var dm;
    if(!domain){
        dm = "";
    } else{
        dm = ";domain=" + domain;
    }

    document.cookie = name + "=" + value + ";path=" + path + e + dm;
}
//计数器
var counter = 0;
/**
 * 加入购物车
 * @param sid 套餐信息
 * @param type 商品类型
 * @param point_value 内容
 * @param expire_days 有效期天数
 * @returns {boolean}
 */
function selectPoint(sid,type,point_value,expire_days) {
    if(sid != undefined) {
        var sid_list = sid.split('_');
        var input_id = "pointtype_" + sid_list[0];
        var input_id_selector = '#'+input_id;
        var id=sid_list[0];                        //当前套餐的ID
        var price = parseInt(sid_list[1]);         //当前套餐的价格
        var package_price = parseInt(sid_list[2]); //当前套餐的电话包
        var cash_card = parseInt(sid_list[3]);     //当前套餐回增的代金券
        var types = ['point','month','classic','book'];
        counter ++;

        if($(input_id_selector).attr('checked')) {
            //更改按钮状态，更改隐藏的checkbox状态
            $(input_id_selector).attr('checked','')
            $('#buy_button_'+sid_list[0]).get(0).className = "btngouwuche";
            //更新购物车
            if(type == 'book'){
                $('#goods-list').find('li[price_id='+id+']').remove();
            }else if(type == 'microphone'){
                $('#goods-list').find('li[price_id='+id+']').remove();
            }else{
                $('#course-list').find('li[price_id='+id+']').remove();
            }
            //更新购买课程或教材数
            if(type == 'book'){
                $('.book-num').text(parseInt($('.book-num').text())-1);
            }else if(type == 'microphone'){
                //不做任何处理
            }else{
                $('.course-num').text(parseInt($('.course-num').text())-1);
            }
            //更新购买课程或教材金额
            if(type == 'book'){
                $('.book-money').text(parseInt($('.book-money').text())-price);
            }else if(type == 'microphone'){
                $('.book-money').text(parseInt($('.book-money').text())-price);
            }else{
                $('.course-money').text(parseInt($('.course-money').text())-price);
            }
            //更新电话包总份额
            $('.package-money').text(parseInt($('.package-money').text())-parseInt(package_price));
            if($('.package-money').text() == 0){
                $('.phone-package').hide();
            }
            //更新购物车内商品数量
            var now_num = parseInt($('.shopping-num-record').text());
            if( now_num > 0 ){
                now_num -= 1;
                if(now_num >0 ){
                    $('.shopping-num-record').text(now_num);
                }else{
                    $('.shopping-num').empty();
                }
            }else{
                $('.shopping-num').empty();
            }
            //更新订单总金额
            $('.total-money').text(parseInt($('.total-money').text())-price);
            if($('.total-money').text()<=0){
                //重置计数器
                counter = 0;
                toggleShoppingBody('close');
                $(".microphone-container").hide();
            }
        }else{
            //更改按钮状态，更改隐藏的checkbox状态
            $(input_id_selector).attr('checked','checked');
            $('#buy_button_'+sid_list[0]).get(0).className = "btnyjgouwuche";
            //更新购物车
            if(type == 'point'){
                $('#course-list').append('<li price_id="'+id+'"><span class="shopping-delete" title="从购物车删除" onclick="selectPoint(\''+sid+'\',\''+type+'\',\''+point_value+'\',\''+expire_days+'\')">&nbsp;</span>次卡学习套餐：'+parseInt(point_value)+'次次卡（'+parseInt(expire_days)+'天有效） 价格：'+price+'元</li>');
            }else if(type == 'month'){
                $('#course-list').append('<li price_id="'+id+'"><span class="shopping-delete" title="从购物车删除" onclick="selectPoint(\''+sid+'\',\''+type+'\',\''+point_value+'\',\''+expire_days+'\')">&nbsp;</span>包月学习套餐：'+parseInt(point_value)+'个月包月（'+parseInt(expire_days)+'天有效） 价格：'+price+'元</li>');
            }else if(type == 'classic'){
                $('#course-list').append('<li price_id="'+id+'"><span class="shopping-delete" title="从购物车删除" onclick="selectPoint(\''+sid+'\',\''+type+'\',\''+point_value+'\',\''+expire_days+'\')">&nbsp;</span>经典小班课学习套餐：'+parseInt(point_value)+'次次卡，小班课无限量（'+parseInt(expire_days)+'天有效） 价格：'+price+'元</li>');
            }else if(type == 'book'){
                $('#goods-list').append('<li price_id="'+id+'"><span class="shopping-delete" title="从购物车删除" onclick="selectPoint(\''+sid+'\',\''+type+'\',\''+point_value+'\',\''+expire_days+'\')">&nbsp;</span>Viki 经典英语教材   Level '+parseInt(point_value)+'  价格：'+price+'元</li>');
            }
            //更新购买课程或教材数
            if(type == 'book'){
                $('.book-num').text(parseInt($('.book-num').text())+1);
            }else if(type == 'microphone'){
                //不做任何处理
            }else{
                $('.course-num').text(parseInt($('.course-num').text())+1);
            }
            //更新购买课程或教材金额
            if(type == 'book'){
                $('.book-money').text(parseInt($('.book-money').text())+price);
            }else if(type == 'microphone'){
                $('.book-money').text(parseInt($('.book-money').text())+price);
            }else{
                $('.course-money').text(parseInt($('.course-money').text())+price);
            }
            //更新电话包总份额
            $('.package-money').text(parseInt($('.package-money').text())+parseInt(package_price));
            if($('.package-money').text() > 0){
                $('.phone-package').show();
            }
            //更新购物车内商品数量
            if($('.shopping-num-record').length == 0){
                $('.shopping-num').html('(<span class="shopping-num-record">1</span>)');
            }else{
                var now_num = parseInt($('.shopping-num-record').text());
                $('.shopping-num-record').text(now_num+1);
            }
            //更新订单总金额
            $('.total-money').text(parseInt($('.total-money').text())+price);
            $('.microphone-container').show();
        }
        if(counter == 1){
            toggleShoppingBody('open');
        }
        //更新价格
        return false;
    }else{
        return false;
    }
}

/*推荐人手机号码是否合法*/
function validate_recommen_mobile() {
    var recommenMobile = $('#recommen_mobile').val();
    var my_mobile      = $('#my_mobile').val();
    if(recommenMobile != '' && recommenMobile != '没有推荐人请留空' && typeof recommenMobile != 'undefined'){
        if(recommenMobile.match(/^1[0-9]{10}$/) == null ) {
            alert('请填写正确的推荐人手机号码，没有推荐人请留空！');
            return false;
        }else if(recommenMobile == my_mobile){
            alert('推荐人手机号码不可以填写成自己的手机号码哦，亲！');
            return false;
        }
    }else{
        return true;
    }
    return true;
}


//添加代金卷新方法
function addCashCardNew(add_cash_card_dialog) {
    var card_id = document.getElementById('discount_id_input').value;
    var price = document.getElementById('total_price').innerHTML;
    if(card_id == '请您选择代金券号码'){
        $.dialog.alert("请您选择代金券号码",{
            autoclose:2000,
            globalBackground:'#E74378',
            lock:false,
            globalBorder:'#E74378 solid 1px'
        });
        return ;
    }
    var str_dis = '';
    $.ajax({
        type: "POST",
        dataType:"json",
        url: "add_cash_card.php",
        data: "card_id=" + card_id+'&price='+price,
        success: function(msg){
            if(msg.status)
            {
                $('#cash_card_list').append('<option value="'+msg.real_card_id+'_'+msg.money+'">'+msg.money+'元&nbsp;&nbsp;&nbsp;'+msg.expire+'到期</option>').val(msg.real_card_id+'_'+msg.money);
                updateCashCard();
                alert( '添加成功' );
                add_cash_card_dialog.hide();
            }else{
                alert( msg.msg );
            }
        }
    });
}


function showGateway()
{
    document.getElementById('gateway_desc').style.display = "";
}

function hiddenGateway()
{
    document.getElementById('gateway_desc').style.display = "none";
}

function showDiv2(divid2,obj)
{
    var obj1 = obj;
    clearTimeout(hidid);
    obj.onmouseout=function(){
        hidid=setTimeout("hideDiv2()",500);
    }

    var layers=$('.altdiv').hide();
    var posLeft = obj1.offsetLeft;
    var posTop = obj1.offsetTop;
    while(obj1=obj1.offsetParent)
    {
        posLeft += obj1.offsetLeft;
        posTop += obj1.offsetTop;
    }
    document.getElementById(divid2).style.display="block";
    var bro=$.browser;
    if(bro.mozilla || bro.opera){
        var clientWidth=document.documentElement.scrollWidth;
    }else{
        var clientWidth=document.body.scrollWidth;
    }

    var divWidth=document.getElementById(divid2).clientWidth;
    if((posLeft+divWidth)>clientWidth){
        posLeft=clientWidth-divWidth-2;
    }
    document.getElementById(divid2).style.left = posLeft+"px";
    document.getElementById(divid2).style.top = posTop + 15+"px";
    document.getElementById(divid2).onmouseover=function(){
        clearTimeout(hidid);
    }
    document.getElementById(divid2).onmouseout=function(){
        hidid=setTimeout("hideDiv2()",500);
    }
}

function hideDiv2()
{
    $('.altdiv').hide()
}

/*
之前购买福袋活动的js
$('#luckpackage').click(function(){
    if($(this).attr('checked')){
        $('#luckybox').slideDown();
    }else{
        $('#luckybox').slideUp();
    }
    if(new Date().getHours() < 10){
        alert('10点钟之后才可以抢哦！');
        return false;
    }
});
$('#secrecy').focus(function(){
    if($(this).val() == '请填写您的邮寄地址'){
        $(this).val('').css('color','#000');
    }
}).blur(function(){
    if($(this).val() == ''){
        $(this).val('请填写您的邮寄地址').css('color','grey');
    }
});*/

/*购物车的显示与隐藏*/
function toggleShoppingBody(action){
    if(action != 'open' && action != 'close'){
        if($('.shopping-slider').html() == '▲'){
            $('.shoppingCart-body').slideDown();
            $('.shopping-slider').html('▼');
        }else{
            $('.shoppingCart-body').slideUp();
            $('.shopping-slider').html('▲');
        }
    }else{
        if(action == 'open'){
            $('.shoppingCart-body').slideDown();
            $('.shopping-slider').html('▼');
        }else{
            $('.shoppingCart-body').slideUp();
            $('.shopping-slider').html('▲');
        }
    }
}
//更新选购麦克风的按键
function shoppingXungouChecked(){
    var checkbox = $(this).prev(':checkbox');
    if(checkbox.attr('checked')){
        checkbox.attr('checked','');
    }else{
        checkbox.attr('checked','checked');
    }
}
//更新课程金额和总金额
function updateCourseMoneyAndTotalMoney(){
    var  package_price = $('.package-money').text();
    if($(this).attr('checked')){
        $('.course-money').text(parseInt($('.course-money').text())+parseInt(package_price));
        $('.total-money').text(parseInt($('.total-money').text())+parseInt(package_price));
    }else{
        $('.course-money').text(parseInt($('.course-money').text())-parseInt(package_price));
        $('.total-money').text(parseInt($('.total-money').text())-parseInt(package_price));
    }
}

//td鼠标离开事件
function dis_onmouse(){
    $('#dis_div').hide("slow");
}
//点击checkbox事件
function dis_radio( data ){
    var strList = $(data).val();
    $('#discount_id').val(strList);
}

//input获取焦点事件
function dis_click(){
    var _total_price = $('#total_price').text();
    if(_total_price < 1000){
        alert('购满1000元才可以使用代金券哦，亲！');
        $(this).removeAttr('checked');
        $('#discount_id').blur();
        return false;
    }
    var input = $('#discount_id');
    var offset = input.offset();
    $('#dis_div').css('left',offset.left + 'px')
        .css('top',offset.top + input.height() + 8 + 'px')
        .css('width',input.width() + 118 +'px')
        .fadeIn();
}
//更改表单中的代金券号
function updateCashCard(){
    var cashcard = $('#cash_card_list').val();
    var cashcard_info = cashcard.split('_');
    $('#cash_card').val(cashcard_info[0]);
    $('#discount_price').text(parseInt($('#total_price').text())-parseInt(cashcard_info[1]));
    if(parseInt(cashcard_info[1]) > 0){
        $('#cash_card_tip').html("您使用了一张<b class='redfont28'><span style='color:red;font-weight:bold; font-size:28px;'>"+cashcard_info[1]+"</span></b>元的代金券").show();
        $('#total-discount').show();
    }else{
        $('#cash_card_tip').html("").hide();
        $('#total-discount').hide();
    }
}

//设置cookie
function setCookie(name, value, expires, path, domain) {
    if(!expires) expires = -1;
    if(!path) path = "/";
    var d = "" + name + "=" + value;

    var e;
    if (expires < 0) {
        e = "";
    } else if (expires == 0) {
        var f = new Date(1970, 1, 1);
        e = ";expires=" + f.toUTCString();
    } else {
        var now  = new Date();
        var f = new Date(now.getTime()  + expires * 86400000);
        e = ";expires=" + f.toUTCString();
    }
    var dm;
    if(!domain){
        dm = "";
    } else{
        dm = ";domain=" + domain;
    }

    document.cookie = name + "=" + value + ";path=" + path + e + dm;
}

$(function(){
    $('.shoppingCart-header').live('click',toggleShoppingBody);
//    $('.shopping-xuangou').live('click',shoppingXungouChecked);
    $('.package').live('click',updateCourseMoneyAndTotalMoney);

    $(':checkbox').attr('checked','');
    //已加入购物车中的商品自动选中
    if(typeof shoppingcard != 'undefined' && shoppingcard != ''){
        var shopping_list = shoppingcard.split(',');
        for(var i = 0;i<shopping_list.length;i++){
            if(shopping_list[i] == 'package'){
                $('.package').click();
            } else if(!isNaN(shopping_list[i])){
                if(shopping_list[i] == microphoneID){
                    $('#microphone_button').click();
                }else{
                    $('#buy_button_'+shopping_list[i]).click();
                }

            }
        }
    }

    /*使用代金券的打开关闭程序*/
    $("#stateDetails").click(function(){
        // 打开前先判断。1000元以下订单不可以使用代金券
        var _total_price = $('#total_price').text();
        if(_total_price<1000){
            alert('购满1000元才可以使用代金券哦，亲！');
            $(this).removeAttr('checked');
            return false;
        }
        var $stateBox = $("#stateDetailsBox");
        if($stateBox.css("display") == 'none') {
            $stateBox.slideDown();
            document.getElementById('stateDetails').innerHTML = "[-]使用代金券";
        } else {
            $stateBox.slideUp();
            document.getElementById('stateDetails').innerHTML = "[+]使用代金券";
        }
    });
    /*提交成功弹出框*/
    $('#submitPay').click(function(){
        if(validate_recommen_mobile()){
            if(!document.getElementById('payMethod_bank').checked)
                jQuery.facybox({ div: '#after_pay_area' });
            $("#ordeForm").submit();
        }
    });

    $('a#closeButton').click(function(){
        jQuery(document).trigger('close.facybox');
    });


    //添加代金卷
    var add_discount_table = $('#add_cash_card_tk').html();
    if($('#add_cash_card_tk')){
        var add_cash_card_dialog = $.dialog.show({container:'#daijinquan',autoOpen:false,showClose:false,title:'输入代金券','content':add_discount_table,globalBackground:'#E74378',lock:false,width:400,offset:{left:0,top:25},globalBorder:'#E74378 solid 1px'},function(){
            add_cash_card_dialog.hide();
        },function(){
            add_cash_card_dialog.hide();
        });
        $('#add_cash_card_tk').empty();
        $('.add_cash_card').click(function(){
            add_cash_card_dialog.show();
        });
        //点击确定提交表单
        var dis_card_val = add_cash_card_dialog.dom.find('.ok')
        add_cash_card_dialog.dom.find('.ok').unbind().live('click',function(){
            addCashCardNew(add_cash_card_dialog);
        })
    }



    $('.input_promo_card').focus(function(){
        if($(this).val() == '请您选择代金券号码'){
            $(this).val('').css('color','#000');
        }
    }).blur(function(){
        if($(this).val() == ''){
            $(this).val('请您选择代金券号码').css('color','#999999');
        }
    });
    $('#cash_card_list').bind('change',updateCashCard);

        $('.microphone-container').hover(
            function(){
                $('.microphone-img').fadeIn(100);
            },function(){
                $('.microphone-img').fadeOut(100);
            })
});



